<?php
/**
 * Created by PhpStorm.
 * user: yzapple
 * Date: 2018/1/8
 * Time: 下午2:08
 */
namespace app\common\library;

use app\common\model\User;
use think\Cookie;
use think\Db;
use think\Exception;
use think\Request;
use think\Session;
use think\Validate;

/**
 * UserAuth类
 */
class UserAuth implements \JsonSerializable, \ArrayAccess
{

    const ERR_ACCOUNT_IS_INCORRECT = '手机号不正确';
    const ERR_ACCOUNT_NOT_EXIST = '手机号不存在';
    const ERR_PHONE_IS_INCORRECT = '手机号不正确';
    const ERR_PASSWORD_IS_INCORRECT = '密码不正确';
    const ERR_PASSWORD_IS_INCORRECT_LENGTH = '密码6-20位';

    const ERR_userNAME_OR_PASSWORD_IS_INCORRECT = '手机号或密码不正确';
    const ERR_PHONE_ALREADY_EXIST = '手机号已存在';
    const ERR_ACCOUNT_IS_LOCKED = '账号禁用';
    const ERR_ACCOUNT_IS_DELETED = '账号已被删除';
    const ERR_PASSWORD_IS_NULL = '密码不能为空';

    const ERR_YOU_ARE_NOT_LOGGED_IN = '您还没有登录';
    const ERR_ACCOUNT_ALREADY_LOGGED_IN_AT_ANOTHER_PLACE = '已在另一端登录';

    protected static $instance = null;
    private $_error = '';
    private $_logined = FALSE;
    private $user = NULL;
    private $keeptime = 0;
    private $requestUri = '';

    public function __construct()
    {
        $this->user = new User;
    }

    /**
     * 初始化
     * @param array $options 参数
     * @return UserAuth
     */
    public static function instance($options = [])
    {
        if (is_null(self::$instance))
        {
            self::$instance = new static($options);
        }

        return self::$instance;
    }

    /**
     *
     * @return user
     */
    public function getModel()
    {
        return $this->user;
    }

    public function __get($name)
    {
        return $this->check() ? $this->user->$name : NULL;
    }

    public function __call($name, $arguments)
    {
        return call_user_func_array([$this->user, $name], $arguments);
    }

    /**
     * 注册用户
     *
     * @param string $username  用户名
     * @param string $password  密码
     * @param string $email     邮箱
     * @param string $mobile    手机号
     * @param string $extend    扩展参数
     * @return boolean
     */
    public function register($phone, $password, $extend = [], $keeptime = 0, $sync = TRUE)
    {
        $rule = [
            'password' => 'require|length:6,20',

            'phone'   => 'regex:/^1\d{10}$/',
        ];

        $msg = [
            'password.require' =>self:: ERR_PASSWORD_IS_NULL,
            'password.length'  =>self::ERR_PASSWORD_IS_INCORRECT_LENGTH,
            'phone'           => self::ERR_PHONE_IS_INCORRECT,
        ];
        $data = [
            'password' => $password,
            'phone'   => $phone,
        ];
        $validate = new Validate($rule, $msg);
        $result = $validate->check($data);
        if (!$result)
        {
            $this->setError($validate->getError());
            return FALSE;
        }

        // 检测用户名或邮箱、手机号是否存在

        if ($phone && User::getByMobile($phone))
        {
            $this->setError(self::ERR_PHONE_ALREADY_EXIST);
            return FALSE;
        }

        $ip = request()->ip();
        $params = array_merge($data, [
            'create_time' => datetime(time()),
            'is_deleted'    => '1'
        ]);
        $params['password'] = md5($password);
        $params = array_merge($params, $extend);



        //账号注册时需要开启事务,避免出现垃圾数据
        Db::startTrans();
        try
        {
            $ret = $this->user->allowField(true)->save($params);
            Db::commit();

            // 此时的Model中只包含部分数据
            $this->user = $this->user->get($this->user->id);

            $this->keeptime($keeptime);
            return $this->syncLogin();
        }
        catch (Exception $e)
        {

            Db::rollback();
            return FALSE;
        }
    }

    /**
     * 用户登录
     *
     * @param string    $account    账号,用户名、邮箱、手机号
     * @param string    $password   密码
     * @param int       $keeptime   有效时长,默认为浏览器关闭
     * @return array
     */
    public function login($account, $password, $keeptime = 0, $sync = TRUE)
    {
        $field =  'phone';
        $user = $this->user->get([$field => $account]);

        if ($user)
        {
            if ($user->is_deleted == '2')
            {
                $this->setError(self::ERR_ACCOUNT_IS_LOCKED);
                return FALSE;
            }
            if ($user->is_deleted == '3')
            {
                $this->setError(self::ERR_ACCOUNT_IS_DELETED);
                return FALSE;
            }

            if ($user->password != $this->getMd5Password($password))
            {
                $this->setError(self::ERR_PASSWORD_IS_INCORRECT);
                return FALSE;
            }

            $this->user = $user;

            // 设置登录有效时长
            $this->keeptime($keeptime);

            return $this->syncLogin($sync);
        }
        else
        {
            $this->setError(self::ERR_ACCOUNT_NOT_EXIST);
            return FALSE;
        }
    }

    /**
     * 注销登录退出
     * @return bool
     */
    public function logout($token = NULL)
    {
        //设置登录标识
        $this->_logined = FALSE;
        Session::delete('yxuid');
        Session::delete('openid');
        $this->user->allowField(true)->save([
            'openid'=>NULL,
            'is_login'=>0,
        ]);

        return TRUE;
    }


    /**
     * 初始化
     *
     * @param int       $user_id    会员ID,默认从Cookie中取
     * @param string    $token      会员Token,默认从Cookie中取
     *
     * @return boolean
     */
    public function init($user_id = NULL, $token = NULL)
    {
        $user_id = $user_id ? $user_id : Session::get('yxuid');
        $user_id = intval($user_id);
        if ($user_id > 0)
        {
            if ($this->_error)
                return FALSE;
            $user = $this->get($user_id);
            if (!$user)
            {
                $this->setError(self::ERR_ACCOUNT_NOT_EXIST);
                return FALSE;
            }
            if ($user['is_deleted'] == 2)
            {
                $this->setError(self::ERR_ACCOUNT_IS_LOCKED);
                return FALSE;
            }
            if ($user['is_deleted'] == 3)
            {
                $this->setError(self::ERR_ACCOUNT_IS_DELETED);
                return FALSE;
            }

            $this->user = $user;
            $this->_logined = TRUE;
            return TRUE;
        }
        else
        {

            $this->setError(self::ERR_YOU_ARE_NOT_LOGGED_IN);
            return FALSE;
        }
    }

    /**
     * 检测是否登录
     *
     * @return boolean
     */
    public function check()
    {
        return $this->_logined;
    }

    /**
     * 检测是否登录
     *
     * @return boolean
     */
    public function isLogin()
    {
        return $this->check();
    }

    /**
     * 获取当前请求的URI
     * @return string
     */
    public function getRequestUri()
    {
        return $this->requestUri;
    }

    /**
     * 设置当前请求的URI
     * @param string $uri
     */
    public function setRequestUri($uri)
    {
        $this->requestUri = $uri;
    }


    /**
     * 直接登录账号
     * @param int $user_id
     * @param boolean $sync
     * @return boolean
     */
    public function direct_openid($openid, $sync = TRUE)
    {
        $this->user = $this->user->where(array('openid'=>$openid))->find();
        if ($this->user)
        {
            $this->syncLogin($sync);
            return TRUE;
        }
        else
        {
            return FALSE;
        }
    }

    /**
     * 直接登录账号
     * @param int $user_id
     * @param boolean $sync
     * @return boolean
     */
    public function direct($user_id, $sync = TRUE)
    {
        $this->user = $this->user->get($user_id);
        if ($this->user)
        {
            $this->syncLogin($sync);
            return TRUE;
        }
        else
        {
            return FALSE;
        }
    }

    /**
     * 获取密码加密方式
     * @param string $password
     * @return string
     */
    public function getMd5Password($password)
    {
        return md5($password);
    }



    /**
     * 检测当前控制器和方法是否匹配传递的数组
     *
     * @param array $arr 需要验证权限的数组
     */
    public function match($arr = [])
    {
        $request = Request::instance();
        $arr = is_array($arr) ? $arr : explode(',', $arr);
        if (!$arr)
        {
            return FALSE;
        }
        // 是否存在
        if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr))
        {
            return TRUE;
        }

        // 没找到匹配
        return FALSE;
    }

    /**
     * 同步登录信息
     * @param int $sync
     * @return boolean
     */
    protected function syncLogin($sync = TRUE)
    {

        //增加登录次数和设置最后登录时间
        $this->user->allowField(true)->save([
            'logintime' => time(),
            'openid'=>session('openid'),
            'is_login'=>1,
        ]);

        // 写入登录Cookies和Token
        $this->writeStatus();
        return TRUE;
    }

    /**
     * 写入登录态和Cookie
     *
     * @param int $keeptime
     */
    protected function writeStatus()
    {
        //设置登录标识
        $this->_logined = TRUE;
        Session::set('yxuid', $this->user->id);
        //加密安全字符
        $this->setError('');
    }

    /**
     * 设置会话有效时间
     * @param int $keeptime 默认为永久
     */
    public function keeptime($keeptime = 0)
    {
        $this->keeptime = $keeptime;
    }


    /**
     * 设置错误信息
     *
     * @param $error
     */
    public function setError($error)
    {
        $this->_error = $error;
        return $this;
    }

    /**
     * 获取错误信息
     * @return string
     */
    public function getError()
    {
        return $this->_error;
    }

    public function __toString()
    {
        return $this->user->toJson();
    }

    // JsonSerializable
    public function jsonSerialize()
    {
        return $this->user->toArray();
    }

    // ArrayAccess
    public function offsetSet($name, $value)
    {
        $this->user->setAttr($name, $value);
    }

    public function offsetExists($name)
    {
        return $this->user->__isset($name);
    }

    public function offsetUnset($name)
    {
        $this->user->__unset($name);
    }

    public function offsetGet($name)
    {
        return $this->user->getAttr($name);
    }

}
